﻿#ifndef THREADPOOL_H
#define THREADPOOL_H

#include <vector>
#include <queue>
#include <thread>
//#include <memory>
#include <functional>
#include <mutex>
#include <condition_variable>

class ThreadPool
{
public:
    ThreadPool(size_t threads)
        : stop(false)
    {
        for(size_t i = 0; i < threads; ++i)
        {
            //初始化线程池
            workerThreads.emplace_back(
                [this] {
                    while(true)
                    {
                        std::function<void()> task;

                        {
                            std::unique_lock<std::mutex> lock(queueMutex);
                            this->condition.wait(lock,  [this]
                                                 { return stop || !tasks.empty(); });

                            if(stop && tasks.empty())
                                return; // 退出线程

                            task = std::move(tasks.front());
                            tasks.pop();
                        }

                        // 执行任务
                        task();
                    }
                }
                );
        }
    }

    ~ThreadPool()
    {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            stop = true;
        }

        condition.notify_all();

        for(std::thread &worker : workerThreads)
        {
            if (worker.joinable())
            {
                worker.join();
            }
        }
    }

    // 禁止拷贝和赋值
    ThreadPool(const ThreadPool&) = delete;
    ThreadPool& operator=(const ThreadPool&) = delete;

    template<class F, class... Args>
    void submit(F&& f, Args&&... args)
    {
        auto task = std::bind(std::forward<F>(f), std::forward<Args>(args)...);

        {
            std::unique_lock<std::mutex> lock(queueMutex);
            if(stop)
                throw std::runtime_error("submit on stopped ThreadPool");

            tasks.emplace(task);
        }
        condition.notify_one();
    }

private:
    std::vector<std::thread> workerThreads;
    std::queue<std::function<void()>> tasks;

    std::mutex queueMutex;
    std::condition_variable condition;
    bool stop;
};

#endif // THREADPOOL_H
